

<template>
  <div class="connectingLine">
    <svg xmlns="http://www.w3.org/2000/svg" version="1.1" ref="svg">
    </svg>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
const props = defineProps({
  // 开始dom
  startDom: {
    type: String,
    default: "",
  },
  // 结束dom
  endDom: {
    type: String,
    default: "",
  },
  // 线条颜色
  stroke: {
    type: String,
    default: "rgb(255,0,0)",
  },
  // 线条宽度
  strokeWidth: {
    type: String,
    default: "1",
  },
  // 虚线间隙
  strokeDasharray: {
    type: String,
    default: "3 2",
  },
})
// 定义接口
interface HtmlAttr {
  [propName: string]: any,
}
// 获取svg dom
const svg: HtmlAttr = ref(null);

// 组件挂载后执行
onMounted(() => {
  // 画线
  drawLine(props.startDom, props.endDom);
})
// 画线
const drawLine = (startDomStr: string, endDomStr: string): void => {
  // 获取dom元素
  const startDom: HTMLElement = document.getElementById(startDomStr) as HTMLElement;
  const endDom: HTMLElement = document.getElementById(endDomStr) as HTMLElement;
  if (startDom && endDom) {
    // 返回被选元素相对于文档的偏移坐标。
    const startX: number = startDom?.offsetLeft + startDom?.clientWidth;
    const startY: number = startDom?.offsetTop + startDom?.clientHeight / 2;
    const endX: number = endDom?.offsetLeft;
    const endY: number = endDom?.offsetTop + endDom?.clientHeight / 2;

    // 绘制line
    let line = document.createElementNS("http://www.w3.org/2000/svg", "line");
    
    line.setAttribute("stroke", props.stroke);
    // stroke 线颜色 stroke-width 线宽度
    line.setAttribute("stroke-width", props.strokeWidth);
    // 画虚线 使用stroke-dasharray="3 2" 属性，其中3和2分别表示画的长度和间隙的长度
    line.setAttribute("stroke-dasharray", props.strokeDasharray);
    line.setAttribute("x1", String(startX));
    line.setAttribute("y1", String(startY));
    line.setAttribute("x2", String(endX));
    line.setAttribute("y2", String(endY));
    svg.value.appendChild(line);
  }

}

</script>

<style lang="less" scoped>
.connectingLine {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
  z-index: 1;

  svg {
    width: 100%;
    height: 100%;
  }
}
</style>
